package com.kgc.sbt.provider;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.kgc.sbt.api.*;
import com.kgc.sbt.domain.Coupon;
import com.kgc.sbt.domain.Goods;
import com.kgc.sbt.domain.OrderInfo;
import com.kgc.sbt.domain.OrderItem;
import com.kgc.sbt.util.RequestResult;
import com.kgc.sbt.util.ResultBuildUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderProvider implements OrderApi {

    @Reference
    private GoodsApi goodsApi;

    @Autowired
    private OrderItemApi orderItemApi;

    @Autowired
    private OrderInfoApi orderInfoApi;

    @Reference
    private CouponLogsApi couponLogsApi;

    @Reference
    private CouponReceiveApi couponReceiveApi;

    @Reference
    private CouponApi couponApi;

    /**
     * 创建订单
     */
    @Override
    public RequestResult<String> createOrder(Integer userId,
                                             Integer addressId,
                                             Integer couponId,
                                             Integer[] goodsId,
                                             Integer[] goodsNum,
                                             String OrderNo,
                                             @RequestParam(required = false) BigDecimal buyLimitPrice) {

        if (goodsId.length != goodsNum.length) {
            return ResultBuildUtil.fail("4001", "无效参数（商品与数量非法）！");
        }

        if (userId == null || addressId == null || goodsId == null || goodsNum == null || goodsId.length == 0 || goodsNum.length == 0) {
            return ResultBuildUtil.fail("4002", "缺失必要参数！");

        }

        if (couponId != 0) {

            //查询优惠券是否存在
            if (!couponReceiveApi.queryCouponByUserIdAndCouponId(userId, couponId)) {
                return ResultBuildUtil.fail("4003", "优惠券不存在或已使用！");
            }
            //判断该优惠券是否可以使在此品类使用
            if (!couponApi.compareUsedAndCid(couponId, goodsId[0])) {
                return ResultBuildUtil.fail("4004", "此优惠券该品类不可用！");

            }

        }


        /**
         * 订单详情表操作
         */
        int num = 0;
        List<OrderItem> orderItemList = new ArrayList<>();

        //总金额
        BigDecimal totalPrice = BigDecimal.valueOf(0);
        while (num < goodsId.length) {

            Goods goods = goodsApi.queryGoodsById(goodsId[num]);
            log.error("--- {} ---",goods);

            if (goods == null){
                return ResultBuildUtil.fail("4007", "商品不存在");
            }

            OrderItem orderItem = new OrderItem();
            //订单编号
            orderItem.setOrderNumber(OrderNo);
            //商品编号
            orderItem.setGoodsId(goodsId[num]);
            //商品名称
            orderItem.setGoodsName(goods.getName());
            //购买数量
            orderItem.setGoodsNum(goodsNum[num]);
            //商品主图
            orderItem.setGoodsUrl(goods.getPicMain());
            //商品单价
            if (buyLimitPrice == null) {
                orderItem.setGoodsPrice(goods.getPrice());
            } else {
                orderItem.setGoodsPrice(buyLimitPrice);
            }

            //计算总金额
            totalPrice = orderItem.getGoodsPrice().multiply(BigDecimal.valueOf(goodsNum[num])).add(totalPrice);


            orderItemList.add(orderItem);
            num++;
        }

        //异步将goodsList插入数据库
        orderItemApi.insertOrderItem(orderItemList);


        /**
         * 订单表操作
         */
        OrderInfo orderInfo = new OrderInfo();
        //订单号
        orderInfo.setOrderNumber(OrderNo);
        //用户id
        orderInfo.setUserId(userId);
        //订单状态编号
        orderInfo.setStatusId(1);//1-待付款
        //地址id
        orderInfo.setAddressId(addressId);
        //订单金额
        orderInfo.setOrderAmount(totalPrice);
        //创建时间
        orderInfo.setCreateTime(new Date());
        orderInfo.setIsUserDelete(0);


        //是否使用优惠券
        if (couponId == 0) {
            //未使用
            orderInfo.setPayAmount(totalPrice);
            orderInfo.setUsedCoupon(0);
        } else if (couponId > 0 && couponId < 10) {

            //使用
            //查询优惠券详情
            Coupon coupon = couponApi.queryCouponById(couponId);
            BigDecimal couponMoney = BigDecimal.valueOf(coupon.getMoney());
            log.error("优惠券金额大于订单金额！{}", orderInfo.getOrderAmount().subtract(couponMoney));
            if (orderInfo.getOrderAmount().subtract(couponMoney).compareTo(BigDecimal.valueOf(0)) == -1) {
                return ResultBuildUtil.fail("4001", "优惠券金额大于订单金额！");
            }
            //set需付款金额
            orderInfo.setPayAmount(orderInfo.getOrderAmount().subtract(couponMoney));//需付款金额（subtract：BigDecimal的减法运算）

            orderInfo.setUsedCoupon(1);

            //异步记录优惠券使用记录
            couponLogsApi.insertCouponLogs(userId, couponId, OrderNo);
            if (!couponReceiveApi.modCouponReceive(userId, couponId)) {
                return ResultBuildUtil.fail("4005", "优惠券无效！");
            }

            coupon.setUsedCount(coupon.getUsedCount() + 1);
            couponApi.updateCouponCountById(coupon);

        } else {
            //报错
            return ResultBuildUtil.fail("4006", "非法参数！");
        }
        //将orderInfo插入数据库
        orderInfoApi.insertOrderInfo(orderInfo);
        return ResultBuildUtil.success("订单生成成功！");
    }
}
